<?php

namespace BinQi\Site;
/**
 *
 */
class Log
{
    // master 线上， dev 开发， test 测试
    protected $env = 'master';

    // info 普通日志， script 脚本， http 请求
    protected $type = 'info';

    // 站点名称（域名）
    protected $site = 'default';

    // 日志存储位置
    protected $logFilePath = './site.log';

    // 模块
    protected $app = 'default';

    // 模块数据
    protected $appData = [];

    // 存储的其他信息
    protected $otherData = [];

    // 处理完的异常信息
    protected $exception = [];

    /**
     * @param $type
     */
    protected function __construct($type = 'info')
    {
        $this->type = $type;
    }

    /**
     * @param $type
     *
     * @return static
     */
    public static function type($type = 'info')
    {
        return new static($type);
    }


    public function appData(array $data, $isMerge = true)
    {
        $this->appData = $isMerge ? array_merge($this->appData, $data) : $data;
    }

    /**
     * @param $data
     * @param $isMerge
     *
     * @return $this
     */
    public function data($data, $isMerge = true)
    {
        $this->otherData = $isMerge ? array_merge($this->otherData, $data) : $data;
        return $this;
    }

    /**
     * @param \Exception $exception
     *
     * @return $this
     */
    public function exception(\Throwable $exception)
    {
        $this->exception = [
            'file'    => $exception->getFile(),
            'line'    => $exception->getLine(),
            'code'    => $exception->getCode(),
            'message' => $exception->getMessage(),
            'trace'   => $exception->getTraceAsString(),
        ];
        return $this;
    }

    /**
     * @return bool
     */
    public function save()
    {
        $status = file_put_contents($this->logFilePath, json_encode(
                array_merge([
                    'site'        => $this->site,
                    'app'         => $this->app,
                    'type'        => $this->type,
                    'exception'   => $this->exception,
                    'other'       => $this->otherData,
                    'create_date' => date('Y-m-d H:i:s'),
                ], $this->appData),
                JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
            ) . PHP_EOL, FILE_APPEND);
        return !!$status;
    }
}